#include <iostream>
#include <string>
#include <mysql/mysql.h>

std::string host = "127.0.0.1";
std::string user = "oo_zz";
std::string passwd = "123456";
std::string db = "test_db";
unsigned int port = 3306;

int main()
{
    std::cout << "mysql client version: " << mysql_get_client_info() << std::endl;
    
    // 数据库初始化
    MYSQL mysql;
    MYSQL* ret1 = mysql_init(&mysql);
    if (ret1 == nullptr)
    {
        std::cerr << "init_error" << std::endl;
        exit(-1);
    }

    // 数据库连接
    MYSQL* ret2 = mysql_real_connect(&mysql, host.c_str(), user.c_str(), passwd.c_str(), db.c_str(), port, nullptr, 0);
    if (ret2 == nullptr)
    {
        std::cerr << "connect_error" << std::endl;
        exit(-1);
    }

    // // 执行增删改
    // std::string sql = "insert into user (name, age) values ('wangwu', 19);";
    // int ret3 = mysql_query(&mysql, sql.c_str());
    // if (ret3)
    // {
    //     std::cerr << "query_error" << std::endl;
    //     exit(-1);
    // }
    // 执行查找
    std::string sql = "select * from  user;";
    int ret4 = mysql_query(&mysql, sql.c_str());
    if (ret4)
    {
        std::cerr << "query_error" << std::endl;
        exit(-1);
    }
    MYSQL_RES* res = mysql_store_result(&mysql);

    int row = mysql_num_rows(res);
    int field = mysql_num_fields(res);
    
    MYSQL_FIELD* fields = mysql_fetch_fields(res);
    for (int i = 0; i < row; i++)
    {
        std::cout << fields[i].name << " ";
    }
    std::cout << "\n";
    
    MYSQL_ROW line;
    for (int i = 0; i < row; i++)
    {
        line = mysql_fetch_row(res);
        for (int j = 0; j < field; j++)
        {
            std::cout << line[j] << " ";
        }
        std::cout << "\n";
    }
    // 关闭数据库
    mysql_close(&mysql);
    return 0;
}